<?php
App::uses('AppModel', 'Model');

class Post extends AppModel {
	Public $name = 'Post';
	public $actsAs = array(
		'Uploader.FileValidation' => array(
			'image' => array(
				'maxWidth' => MAX_IMAGE_UP_WIDTH,
				'maxHeight' => MAX_IMAGE_UP_HEIGHT,
				'extension' => array('gif', 'jpg', 'png', 'jpeg'),
				'type' => 'image',
				'filesize' => MAX_IMAGE_UP_SIZE,
				'required' => false
			)
		),
		'Uploader.Attachment' => array(
			'image' => array(
 				'nameCallback' => 'formatName',
 				'uploadDir' => MEDIA_IMAGE_PATH_ORIGINAL,
 				'finalPath' => '',
 				'dbColumn' => 'image',
 				'transforms' => array(
					'large' => array(
						'method' => 'resize',
 						'nameCallback' => 'transformName',
 						'uploadDir' => MEDIA_IMAGE_PATH_LARGE,
						'overwrite' => true,
						'quality' => UPLOAD_IMAGE_QUALITY,
						'width' => MAX_IMAGE_WIDTH,
						'height' => MAX_IMAGE_HEIGHT,
						'expand' => false,
						'aspect' => true,
						'mode' => 'width',
					)
 				),
			)
		)
	);

	public function formatName($name, $file) {
		return time() . rand(0, 1000);
	}

	public function transformName($name, $file) {
		return $this->getUploadedFile()->name();
	}

	public $validate = array(
		'title' => array(
			'rule' => 'notEmpty',
			'required' => true
		),
		'description' => array(
			'rule' => 'notEmpty',
			'required' => true
		),
	);

	public function validateAccess() {
		if (empty($_SERVER['REMOTE_ADDR'])) {
			return false;
		}

		$postsCount = $this->find('count', array(
			'conditions' => array(
				'Post.ip_address' => $_SERVER['REMOTE_ADDR'],
				'Post.created >' => date('Y-m-d H:i:s', strtotime('-1 hour'))
			)
		));

		return ($postsCount >= 3) ? false : true;
	}
}
